package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrdersSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.dto.SubmitDTO;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.pojo.entity.Order;
import com.itheima.health.pojo.entity.OrderSetting;
import com.itheima.health.pojo.vo.OrderFindByIdVO;
import com.itheima.health.service.OrderService;

import com.itheima.health.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private MemberDao memberDao;

   @Autowired
   private RedisTemplate redisTemplate;

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrdersSettingDao ordersSettingDao;

//    @Autowired
//    private AliSmsProperties aliSmsProperties;


    /**
     * 根据id查询订单id
     *
     * @param id
     * @return
     */
    @Override
    public OrderFindByIdVO findById(String id){
        OrderFindByIdVO vo = orderDao.findById(id);
        return vo;
    }

    /**
     * 预约订单提交
     * @param submitDTO
     * @return
     */
    @Override
    public Order submit(SubmitDTO submitDTO){
        // 验证码正确，日期必须填写
        //从redis中获取验证码进行验证
        String code =(String) redisTemplate.opsForValue().get(RedisConst.ORDER + submitDTO.getTelephone());

        if (!Objects.equals(submitDTO.getValidateCode(), code)){
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }
        // 不是会员自动注册为会员
        Member memberTemp = memberDao.selectByName(submitDTO.getName());
        Member member = null;
        Integer memberId;
        Order order = new Order();
        if (memberTemp == null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            Date idCard;
            try{
                 idCard = simpleDateFormat.parse(submitDTO.getIdCard().substring(6, 14));
            }catch (ParseException e){
                log.warn("身份证号有误{}",e.getMessage());
                throw new BusinessRuntimeException(MessageConst.ID_NUMBER_IS_INVALID);
            }


            member = Member.builder()
                    .name(submitDTO.getName())
                    .sex(submitDTO.getSex())
                    .idCard(submitDTO.getIdCard())
                    .phoneNumber(submitDTO.getTelephone())
                    .regTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()))
                    .birthday(idCard)
                    .build();
            memberDao.insert(member);
            memberId = member.getId();
        }
        else {
            memberId = memberTemp.getId();
        }

        // 会员同一天同一套餐不能重复预约
        Integer count = orderDao.selectCountByMemberAndSetmeal(memberId, submitDTO.getSetmealId(), submitDTO.getOrderDate());
        log.info("当天预约数量为{}",count);
        if (count > 0 ){
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        // 体检人姓名是否为空
        if (submitDTO.getName() == null || submitDTO.getOrderDate() == null){
            throw new BusinessRuntimeException(MessageConst.User_Information_Cannot_Be_Empty);
        }else {
            // 该体检预约是否已经约满
            OrderSetting orderSetting = ordersSettingDao.selectByDate(submitDTO.getOrderDate());
            if (!ObjectUtils.isEmpty(orderSetting) ){
                if (orderSetting.getNumber() <= orderSetting.getReservations() ) {
                    throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
                }
            }

        }

        // 提交逻辑
        order.setMemberId(memberId);
        LocalDate localDate = submitDTO.getOrderDate();
        // 转换为 LocalDateTime
        LocalDateTime localDateTime = localDate.atStartOfDay();
        // 转换为 Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        order.setOrderDate(date);
//            order.setOrderType(submitDTO.getOrderType());
        order.setSetmealId(Integer.valueOf(submitDTO.getSetmealId()));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        orderDao.insert(order);
        // 补充id
        order.setId(order.getId());

        return order;
    }

    /**
     * 根据id查询订单
     * @param id
     * @return
     */
    public Order FindById(String id) {
        log.info("根据ID查询订单：{}",id);
        return (Order) orderDao.selectById(id);
    }


    /**
     * 发送手机验证码
     * @param type
     * @param telephone
     */

//    private static final String CODE = "VALID_CODE";
//
//    // todo
//    private String telephone = "15769310936";
//    private String validCode;
//    @Override
//    public void sendValidateCode(String type, String telephone) {
//        String uuid = UUID.randomUUID().toString().replaceAll("\\D", "").substring(0, 4);
//        // 测试短信服务只支持数字组合、不支持字母数组合发送
//        String validCode = "{\"code\":\"" + uuid + "\"}";
//        redisTemplate.opsForValue().set(CODE, uuid);
//        this.validCode = uuid;
//        try {
//            AliSmsUtils.sendMessage(aliSmsProperties.getSignName(), aliSmsProperties.getTemplateCode(), this.telephone, validCode);
//        } catch (Exception e) {
//            throw new BusinessRuntimeException(MessageConst.SEND_VALIDATECODE_FAIL);
//        }
//    }
}
